package com.yls.audiotester;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class VolumeAdjustActivity extends AppCompatActivity {

    private TextView mCurrentVolumeTextView;
    private int mCurrentVol, mMaxVol, mMinVol;
    private AudioManager mAudioManager;
    private static final int MY_STREAM_TYPE = AudioManager.STREAM_MUSIC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_volume_adjust);

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMaxVol = mAudioManager.getStreamMaxVolume(MY_STREAM_TYPE);
        mMinVol = mAudioManager.getStreamMinVolume(MY_STREAM_TYPE);

        initViews();
    }

    private void initViews() {
        mCurrentVolumeTextView = findViewById(R.id.current_vol_text);
        Button addVol = findViewById(R.id.add_vol);
        Button reduceVol = findViewById(R.id.reduce_vol);

        addVol.setOnClickListener(v -> setVolume(calculateVolume(true)));
        reduceVol.setOnClickListener(v -> setVolume(calculateVolume(false)));
    }

    @Override
    protected void onStart() {
        super.onStart();
        updateVolume();
    }

    @SuppressLint("DefaultLocale")
    private void updateVolume() {
        mCurrentVol = mAudioManager.getStreamVolume(MY_STREAM_TYPE);
        if (mCurrentVolumeTextView != null) {
            mCurrentVolumeTextView.setText(String.format("当前音量：%d", mCurrentVol));
        }
    }

    private int calculateVolume(boolean add) {
        if (add) {
            return Math.min(mMaxVol, mCurrentVol + 1);
        } else {
            return Math.max(mMinVol, mCurrentVol - 1);
        }
    }

    private void setVolume(int vol) {
        mAudioManager.setStreamVolume(MY_STREAM_TYPE, vol, AudioManager.FLAG_SHOW_UI);
        updateVolume();
    }
}